const jwt = require("jsonwebtoken")
const db = require("../db")
const Router = require("@koa/router")

const router = new Router();

router.prefix('/user')

router.post('/login', async (ctx, next) => {
    const { username, password } = ctx.request.body
    const isPass = await db.checkUser(username, password)
    if (isPass) {
        let token = jwt.sign({ username }, "2302B")
        ctx.body = {
            success: true,
            msg: '登录成功',
            data: { token }
        }
    } else {
        ctx.body = {
            success: false,
            data: {
                ctx: ctx.request,
                username, password
            }
        }
    }
})

router.post('/register', async (ctx, next) => {
    const { username, password } = ctx.request.body
    const registerInfo = await db.register(username, password)
    ctx.body = {
        success: true, data: {
            registerInfo
        },
    }
})

module.exports = router